<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item>{{ $t('Home') }}</el-breadcrumb-item>
    <el-breadcrumb-item>{{ $t('BlockChain') }}</el-breadcrumb-item>
    <el-breadcrumb-item>{{ $t('DAOOnline') }}</el-breadcrumb-item>
  </el-breadcrumb>
  <div class="community-list">
    <!-- 搜索组件 -->
    <div class="search-bar">
      <el-input v-model="searchQuery" :placeholder="$t('community.enter_community_name')" clearable />
      <el-button type="primary" @click="searchCommunities">{{ $t('search') }}</el-button>
      <el-button type="success" @click="showAddCommunityDialog = true">{{ $t('community.add_community') }}</el-button>
    </div>

    <el-card v-for="community in communities" :key="community.community_id" class="community-card">
      <template #header>
        <div class="card-header">
          <img :src="config.getUrl(community.logo_url)" alt="Community Logo" class="community-logo" />
          <span>{{ community.community_name }}</span>
          <el-button type="primary" size="small" class="enter-button" @click="enterCommunity(community)">
            {{ $t('enter') }}
          </el-button>
        </div>
      </template>
      <el-descriptions :column="1" size="small" class="community-details">
        <el-descriptions-item :label="$t('community.description')">
            <span style="word-break: break-all;">{{ community.description }}</span>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('community.creator')">
          <span class="creator">{{ community.creator }}</span>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('community.created_at')">{{ config.formatTime(community.created_at) }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>

  <!-- 新增社区弹窗 -->
  <el-dialog :title="$t('community.add_community')" v-model="showAddCommunityDialog" width="40%">
    <el-form :model="newCommunity" label-width="160px">
      <el-form-item :label="$t('community.community_id')">
        <el-input v-model="newCommunity.community_id"></el-input>
      </el-form-item>
      <el-form-item :label="$t('community.community_name')">
        <el-input v-model="newCommunity.community_name"></el-input>
      </el-form-item>
      <el-form-item :label="$t('community.description')">
        <el-input v-model="newCommunity.description" type="textarea"></el-input>
      </el-form-item>
      <el-form-item :label="$t('community.logo_url')">
        <image-upload v-model="images" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showAddCommunityDialog = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="createCommunity">{{ $t('confirm') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElCard, ElInput, ElButton, ElDialog, ElForm, ElFormItem } from 'element-plus';
import { useI18n } from 'vue-i18n';
import eventBus from '@/utils/eventbus';
import ApiClient from '@/api/ApiClient';
import { ApiRequest, ApiRequestBody } from '@/api/ApiRequest';
import { ApiResponse } from '@/api/ApiResponse';
import { config } from '@/config/config';
import { Community } from '@/model/Community';
import ImageUpload from '@/components/ImageUpload.vue';
import { useRouter } from 'vue-router';

const { t } = useI18n();
const router = useRouter();
const communities = ref<Community[]>([]);
const searchQuery = ref('');
const showAddCommunityDialog = ref(false);
const newCommunity = ref({
  community_id: '',
  community_name: '',
  description: '',
  admin_ids: []
});
const images = ref<{ name: string, url: string }[]>([]);

const fetchCommunities = async (name: string = '') => {
  try {
    const request = new ApiRequest(
        "query",
        config.dao_chain_name,
        new ApiRequestBody(
            config.dao_contract_name,
            "search_community",
            {
              "community_name": name
            }
        )
    );
    ApiClient.sendSync(request, (response: ApiResponse) => {
        if(response.data.code_value as unknown as number == 0){
            const contractResult = response.data.contract_result as { [key: string]: string };
            communities.value = JSON.parse(contractResult.result);
        }else{
            ElMessage.error(response.data.code);
        }
    });
  } catch (error) {
    console.error('Error fetching communities:', error);
  }
};

const searchCommunities = () => {
  fetchCommunities(searchQuery.value);
};

onMounted(() => {
  fetchCommunities();
});

const enterCommunity = (community: Community) => {
  localStorage.setItem("community", JSON.stringify(community));
  eventBus.emit('communityChange', community);
  router.push('/dao');
}

const createCommunity = () => {
  // 调用 API 创建新社区
  const request = new ApiRequest(
    "invoke",
    config.dao_chain_name,
    new ApiRequestBody(
      config.dao_contract_name,
      "save_community",
      {
        "community_id": newCommunity.value.community_id,
        "community_name": newCommunity.value.community_name,
        "description": newCommunity.value.description,
        "logo_url": images.value[0].url.replace(config.ipfs_gateway, 'ipfs://'),
        "admin_ids": JSON.stringify(newCommunity.value.admin_ids)
      }
    )
  );
  ApiClient.sendSync(request, (response: ApiResponse) => {
    if (response.data.code_value as unknown as number == 0) {
      ElMessage.success(t('community.created_successfully'));
      showAddCommunityDialog.value = false;
      fetchCommunities(); // 刷新社区列表
    } else {
      ElMessage.error(response.data.code);
    }
  });
};
</script>

<style scoped>
/* 整体容器样式 */
.community-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 16px;
  min-height: calc(100vh - 60px);
  align-content: flex-start;
}

/* 搜索栏样式优化 */
.search-bar {
  width: 100%;
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  padding: 8px 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  align-items: center;
  height: 48px;
  overflow: hidden;
}

/* 搜索框宽度控制 */
.search-bar .el-input {
  width: 300px;
  flex-shrink: 0;
}

/* 按钮样���调整 */
.search-bar .el-button {
  height: 32px;
  padding: 0 16px;
  flex-shrink: 0;
}

/* 社区卡片样式优化 */
.community-card {
  width: calc(33.33% - 12px);
  height: 225px;
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.community-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: linear-gradient(to right, #f0f2f5, #ffffff);
  flex-shrink: 0;
}

/* 社区logo样式 */
.community-logo {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 社区名称样式 */
.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 进入按钮样式 */
.enter-button {
  margin-left: auto;
  border-radius: 20px;
  padding: 8px 20px;
  font-weight: 500;
}

/* 社区详情样式 */
.community-details {
  padding: 8px 12px;
  flex: 1;
  overflow-y: auto;
}

:deep(.el-descriptions__cell) {
  padding-bottom: 4px;
  display: flex !important;
  align-items: center;
}

:deep(.el-descriptions__label) {
  color: #606266;
  font-weight: 500;
  width: 80px !important;
  flex-shrink: 0;
}

:deep(.el-descriptions__content) {
  color: #303133;
  line-height: 1.6;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: calc(100% - 80px);
}

:deep(.el-descriptions__content.creator) {
  max-width: 200px;
}

/* 添加社区对话框样式 */
:deep(.el-dialog) {
  border-radius: 16px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin-right: 0;
  background: #f5f7fa;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .community-card {
    width: calc(50% - 8px);
  }
}

@media screen and (max-width: 768px) {
  .community-card {
    width: 100%;
  }
  
  .search-bar {
    overflow-x: auto;
    flex-wrap: nowrap;
  }
  
  .search-bar .el-input {
    width: 200px;
  }
}
</style>